package com.baixun.gascommon.utils;

import com.baixun.gascommon.exception.NoUserIdException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义http拦截器
 */
@Component
public class HttpInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        String requestURI = request.getRequestURI();
        //放行登录接口
        if (requestURI.equals("/user/login") || requestURI.equals("/error")){
            return true;
        }
        if (userId == null){
            throw new NoUserIdException("请传入userId");
        }
        //保存当前线程变量
        ThreadLocalUtils.setThreadLocal(Long.parseLong(userId));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
